package com.hzz.web.boss.user;

import com.hzz.api.user.IAuthRoleService;
import com.hzz.api.user.IRoleSourceService;
import com.hzz.dto.user.AuthRoleDto;
import com.hzz.dto.user.UserDto;
import com.hzz.framework.PageUtil;
import com.hzz.framework.Response;
import com.hzz.framework.annotation.ALogOperation;
import com.hzz.framework.annotation.auth.Logical;
import com.hzz.framework.annotation.auth.RequiresPermissions;
import com.hzz.framework.util.CommonConstant;
import com.hzz.framework.util.JwtUtil;
import com.hzz.framework.web.controller.BaseController;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api("用户角色管理")
@RestController
@Slf4j
public class AuthRoleController extends BaseController {
    private static final long serialVersionUID = -528422099490438672L;
    private static final String acPrefix = "/boss/staff/authRole/";
    @Autowired
    IAuthRoleService authRoleService;
    @Autowired
    IRoleSourceService roleSourceService;

    /**
     * <p>信息分页 (未删除)。
     */
    @RequiresPermissions("user:edit:role")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "page/{pageNum}")
    // @ApiOperation(value = "信息分页")
    public Response page(@ModelAttribute AuthRoleDto dto, @PathVariable("pageNum") Integer pageNum) {
        log.info("page.........");
        Response result = new Response();
        try {
            dto.setPageSize(CommonConstant.PAGEROW_DEFAULT_COUNT);
            dto.setPageNum(pageNum);
            dto.setDelFlag(0);
            // 信息列表
            result.data = PageUtil.copy(authRoleService.findDataIsPage(dto));
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    /**
     * <p>信息分页 (未删除)。
     */
    @RequiresPermissions("user:edit:role")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "list")
    // @ApiOperation(value = "信息分页")
    public Response list(@ModelAttribute AuthRoleDto dto) {
        log.info("page.........");
        Response result = new Response(0, "success");
        try {
            if (dto == null) {
                dto = new AuthRoleDto();
            }
            dto.setDelFlag(0);
            // 信息列表
            result.data = authRoleService.findDataIsList(dto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    /**
     * <p> 信息详情。
     */
    @RequiresPermissions("user:edit:role")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "info/{id}")
    // @ApiOperation(value = "信息详情")
    public Response info(@PathVariable("id") Long id) {
        log.info("info.........");
        Response result = new Response();
        try {
            AuthRoleDto dto = new AuthRoleDto();
            if (id != null) {
                dto.setId(id);
                dto.setDelFlag(0);
                result.data = authRoleService.findDataById(dto);
            }
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    /**
     * <p>删除。
     */
    @RequiresPermissions("user:edit:role")
    @RequestMapping(method = RequestMethod.POST, value = acPrefix + "del/{id}")
    @ALogOperation(type = "删除", desc = "用户角色管理")
    // @ApiOperation(value = "信息删除")
    public Response del(@PathVariable("id") Long id) {
        log.info("del.........");
        Response result = new Response(0, "success");
        try {
            AuthRoleDto dto = new AuthRoleDto();
            dto.setId(id);
            if (id <= 4) {
                return Response.error("系统锁定角色,不能删除!");
            }
            result.message = authRoleService.deleteDataById(dto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

//    /**
//     * <p> 信息保存
//     */
//    @RequiresPermissions(value = {"authRole:add", "authRole:edit", "user:edit:role"}, logical = Logical.OR)
//    @RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT}, value = acPrefix + "save")
//    @RfUser2Bean
//    @ALogOperation(type = "修改", desc = "用户角色管理")
//    // @ApiOperation(value = "信息保存")
//    public Response save(@Validated @ModelAttribute AuthRoleDto dto, BindingResult bindingResult) {
//        log.info("save.........");
//        Response result = new Response(0, "success");
//        try {
//            if (dto == null) {
//                return Response.error("参数获取异常!");
//            }
////            if ("1".equals(request.getSession().getAttribute(acPrefix + "save." + dto.getToken()))) {
////                throw new RuntimeException("请不要重复提交!");
////            }
//            if (bindingResult.hasErrors()) {
//                String errorMsg = "";
//                List<ObjectError> errorList = bindingResult.getAllErrors();
//                for (ObjectError error : errorList) {
//                    errorMsg += (error.getDefaultMessage()) + ";";
//                }
//                result = Response.error(errorMsg);
//            } else {
//                result = authRoleService.saveOrUpdateData(dto);
////                request.getSession().setAttribute(acPrefix + "save." + dto.getToken(), "1");
//            }
//        } catch (Exception e) {
//            result = Response.error(e.getMessage());
//        }
//        return result;
//    }

    /**
     * <p> 信息保存
     */
    @RequiresPermissions("user:edit:role")
    @RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT}, value = acPrefix + "update")
    @ALogOperation(type = "修改", desc = "用户角色管理")
    // @ApiOperation(value = "信息保存")
    public Response update(@Validated @ModelAttribute AuthRoleDto dto, BindingResult bindingResult) {
        log.info("update.........");
        Response result = new Response(0, "success");
        try {
            if (bindingResult.hasErrors()) {
                String errorMsg = "";
                List<ObjectError> errorList = bindingResult.getAllErrors();
                for (ObjectError error : errorList) {
                    errorMsg += (error.getDefaultMessage()) + ";";
                }
                result = Response.error(errorMsg);
            } else {
                result = authRoleService.saveOrUpdateData(dto);
            }
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    @RequiresPermissions(value = {"user:edit:role"}, logical = Logical.OR)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "perm")
    // @ApiOperation(value = "获取当前角色已有(功能/权限)")
    public Response perm(@RequestParam(name = "roleId") Long roleId) {
        log.info("perm.........");
        Response result = new Response(0, "success");
        try {
            AuthRoleDto dto = new AuthRoleDto();
            dto.setId(roleId);
            result.data = authRoleService.findPermIsList(dto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    /**
     * <p>员工角色
     */
    @RequiresPermissions("user:edit:role")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "staffRole")
    @ResponseBody
    // @ApiOperation(value = "员工角色")
    public Response staffRoleList() {
        log.info("staffRoleList.........");
        Response result = new Response(0, "success");
        try {
            // 信息列表
            UserDto staffDto = JwtUtil.getSubject(UserDto.class);
            result.data = roleSourceService.getRoleListByUserId(staffDto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

}